<?php

namespace app\common\logic\meet;

use addons\litestore\model\Litestoreorder;
use addons\third\model\Third;
use app\common\library\wechat\Wechat;
use app\common\model\meet\Config;
use app\common\model\meet\Fans;
use app\common\model\meet\Store;
use app\common\model\User;
use EasyWeChat\Factory;

class Message
{
    /**
     * 商城-下单成功发送消息
     */
    public function mallOrderPay($order_id)
    {
        $model = new Litestoreorder();

        $order = $model->with('goods')->where('id', $order_id)->find();

        if (empty($order)) {
            return false;
        }

        //门店关联接收订单消息的用户
        $receive_user_ids = Store::where('id', $order['store_id'])->value('receive_user_ids');

        if (empty($receive_user_ids)) {
            return false;
        }

        $receive_user_ids_arr = explode(',', $receive_user_ids);

        foreach ($receive_user_ids_arr as $user_id) {
            $message_info = $this->getMessageInfo('MALL_ORDER_NEW_REMINDER', $user_id);

            if (empty($message_info)) {
                break;
            }

            $nickname = User::where('id', $order['user_id'])->value('nickname');

            $data = [
                'openid' => $message_info['openid'],
                'template_id' => $message_info['data']['template_id'],
                'url' => '',
                'miniprogram' => [],
                'data' => [
                    'character_string1' => $order['order_no'],
                    'thing7' => $nickname,
                    'amount17' => '￥' . (float)$order['pay_price'],
                    'time4' => $order['pay_time_text'],
                ]
            ];

            $this->sendMessage($data);
        }

        return true;
    }

    /**
     * 预约-下单成功发送消息
     */
    public function meetOrderPay($order_id)
    {
        $model = new \app\common\model\meet\Order();

        $order = $model->with('products')->where('id', $order_id)->find();

        if (empty($order)) {
            return false;
        }

        //门店关联接收订单消息的用户
        $receive_user_ids = Store::where('id', $order['store_id'])->value('receive_user_ids');

        if (empty($receive_user_ids)) {
            return false;
        }

        $product_name = '';
        foreach ($order['products'] as $product) {
            $product_name .= $product['product_name'] . ';';
        }

        $product_name = mb_substr(rtrim($product_name, ';'), 0, 20, 'UTF-8');

        $receive_user_ids_arr = explode(',', $receive_user_ids);

        foreach ($receive_user_ids_arr as $user_id) {
            $message_info = $this->getMessageInfo('MEET_ORDER_NEW_REMINDER', $user_id);

            if (empty($message_info)) {
                break;
            }

            $data = [
                'openid' => $message_info['openid'],
                'template_id' => $message_info['data']['template_id'],
                'url' => '',
                'miniprogram' => [],
                'data' => [
                    'character_string10' => $order['order_no'],
                    'thing9' => $order['nickname'],
                    'thing12' => $product_name,
                    'time4' => $order['reservation_time_text'],
                    'amount5' => '￥' . $order['pay_price']
                ]
            ];

            $this->sendMessage($data);
        }

        return true;
    }

    public function sendMessage($data)
    {
        try {
            $app = Factory::officialAccount(Wechat::getConfig());

            $result = $app->template_message->send([
                'touser' => $data['openid'], // openid
                'template_id' => $data['template_id'],// 模板id
                'url' => $data['url'],// 跳转链接
                'miniprogram' => isset($data['miniprogram']) ? $data['miniprogram'] : [], // 跳转小程序  ['appid' => 'xxxxxxx','pagepath' => 'pages/xxx',]
                'data' => $data['data'] // 模板变量
            ]);
        } catch (\Exception $e) {
            return false;
        }

        if (isset($result['errcode']) && $result['errcode'] != 0) {
            $this->error = $result["errmsg"];
            return false;
        }

        return true;
    }

    public function getMessageInfo($keywords, $user_id)
    {
        $message_info = (new \app\common\model\meet\Message())->where(['keywords' => $keywords, 'status' => \app\common\model\meet\Message::STATUS_NORMAL])->find();

        if (empty($message_info)) {
            return false;
        }

        if ((int)$user_id) {
            $unionid = Third::where('user_id', $user_id)->value('unionid');

            if (empty($unionid)) {
                return false;
            }

            $openid = Fans::where('unionid', $unionid)->value('openid');

            if (empty($openid)) {
                return false;
            }
        } else {
            $openid = $user_id;
        }

        return ['openid' => $openid, 'data' => $message_info];
    }
}